import React, { useEffect, useState } from 'react';
import { useStore } from '@/hooks';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import { ENUMS, column } from '../stores/definitions';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { Tab, Radio, Button } from '@alifd/next';

const RadioGroup = Radio.Group;

const NewTable = () => {
  const { busStationStore: store } = useStore();
  const [companyData, setCompanyData] = useState([]); // 公司选择参数 支持滚动到底部加载
  const [page, setPage] = useState(0);
  const [selectData, setSelectData] = useState([]);
  const [city, setCity] = useState([]);
  const [radioValue, setRadioValue] = useState(false);

  useEffect(() => {
    (async () => {
      const res = await store.getCompany({ search: { isOperating: true }, pg: { page, size: 10 } });
      const res2 = await store.getCity({ companyId: '', type: 0 });
      setCompanyData(res);
      setCity(res2);
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    // console.log('params:', params);
    const { range, ...search } = params.values;
    store.other_search = {
      range,
      ...search,
    };
  };

  const handleOnScroll = async (e) => {
    const { scrollHeight } = e.target;
    const { clientHeight } = e.target;
    const { scrollTop } = e.target;
    if (scrollTop + clientHeight === scrollHeight) {
      const currentPage = page + 1;
      const otherData = await store.getCompany({ search: {}, pg: { page: currentPage, size: 10 } });
      setCompanyData((pre) => pre.concat(otherData));
      setPage(currentPage);
    }
  };

  /**
   * 勾选第三方站点时的处理函数
   * @param {*} e 勾选的站点id数组
   * @param {*} r 勾选的站点源数据数组
   */
  const handleSelectChange = (e, r) => {
    const tmpData = e.map((p) => p.split('-')[1]);
    // 使用唯一标识符存储选中的数据
    const newSelectedData = { ...selectData };
    r.forEach((item) => {
      newSelectedData[item.stationId] = item; // 假设每条数据有唯一标识符 `id`
    });
    const filteredData = Object.keys(newSelectedData)
      .filter((key) => tmpData.includes(key))
      .reduce((obj, key) => {
        obj[key] = newSelectedData[key];
        return obj;
      }, {});
    setSelectData(newSelectedData);
    store.selectStationInfos = filteredData;
  };

  const handleTabChange = (e) => {
    store.stationStatus = e;
  };

  const handleRadio = async (e) => {
    setRadioValue(e);
    store.relate = e;
  };

  return (
    <div>
      <TauActionPanel
        className="action-panel"
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'companyId',
            type: 'select',
            props: {
              placeholder: t`公司搜索`,
              dataSource: companyData,
              style: { minWidth: '160px' },
              menuProps: { onScroll: handleOnScroll },
              autoHighlightFirstItem: false,
            },
          },
          {
            name: 'cityName',
            type: 'select',
            props: {
              placeholder: t`城市`,
              changeOnSelect: true,
              dataSource: city,
              style: { minWidth: '160px' },
            },
          },
        ].concat(
          store._stationType === '1'
            ? [
              {
                name: 'range',
                type: 'input',
                props: {
                  placeholder: t`指定范围(公里)`,
                  style: { width: '140px' },
                },
              },
            ]
            : [],
        )}
        keywordSearch={{
          placeholder: t`请输入关键字搜索`,
          enabled: true,
        }}
      />
      <div>
        <Tab
          activeKey={store.stationStatus}
          onChange={handleTabChange}
          extra={
            <RadioGroup
              dataSource={ENUMS.RADIO_LIST}
              shape="button"
              value={radioValue}
              onChange={handleRadio}
            />
          }
        >
          {ENUMS._TABS_TYPE.map(({ key, name }) => (
            <Tab.Item key={key} title={name} />
          ))}
        </Tab>
      </div>
      <TauTable
        primaryKey="proKey"
        tableLayout="fixed"
        currentPage={store.other_pg.page}
        pageSize={store.other_pg.size}
        total={store.other_total}
        sort={store.tableSort}
        onFetch={(pg) => {
          store.other_pg = pg;
        }}
        loading={store.other_loading}
        dataSource={toJS(store.other_stations)}
        hidePagination={store._stationType === '1'}
        rowSelection={{
          onChange: (e, r) => handleSelectChange(e, r),
          columnProps: () => {
            return {
              lock: 'right',
              width: 38,
              align: 'center',
            };
          },
        }}
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._other_idx(i * 2) },
          column('companyName', {}),
          column('cityName', {}),
          column('areaName', {}),
          column('stationId', {}),
          column('name', {}),
          column('tableKind', {}),
          column('addressText', {}),
          column('longLat', {}),
        ]}
      />
    </div>
  );
};

export default observer(NewTable);
